import React, { FC, useState } from 'react'
import { Button, Form, Input, Image, message } from 'antd'
import axios from '@/http'
const LinkAdd: FC<{ closeModal: () => void; getLinkList: () => void }> = ({ closeModal, getLinkList }) => {
  const [picture, setPicture] = useState<string>('')
  const [form] = Form.useForm()
  const initValue = {
    title: '',
    url: '',
    description: '',
    img: ''
  }
  const onFinish = (values: any) => {
    axios.post('/link/add', { ...values }).then((res) => {
      console.log(res)
      if (res.data.error === -1) {
        getLinkList()
        message.success('添加成功')
        reset()
        closeModal()
      } else {
        message.error('添加失败')
      }
    })
  }
  const reset = () => {
    form.resetFields()
    setPicture('')
  }
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo)
  }
  const showPicture: React.FocusEventHandler<HTMLInputElement> = (e) => {
    setPicture(e.target.value)
  }
  return (
    <div>
      <Form
        form={form}
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={initValue}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off">
        <Form.Item label="友链名称" name="title" rules={[{ required: true, message: '请输入标题!' }]}>
          <Input />
        </Form.Item>
        <Form.Item label="网址" name="url" rules={[{ required: true, message: '请输入网址!' }]}>
          <Input />
        </Form.Item>
        <Form.Item label="描述" name="description">
          <Input />
        </Form.Item>
        <Form.Item label="图片" name="img">
          <Input onChange={showPicture} />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Image src={picture} alt="预览图片" width={300} height={160} />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
          <Button type="default" onClick={reset} style={{ marginLeft: '48px' }}>
            重制
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}
export default LinkAdd
